import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_all.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/models/xindong_tag_class.dart';
import 'package:xindong/routes/tab_mine/xindong_wode_http.dart';
import 'package:xindong/utils/xindong_text_util.dart';
import 'package:xindong/widgets/common/xindong_app_bar.dart';
import 'package:xindong/widgets/common/xindong_common_widget.dart';
import 'package:xindong/widgets/common/xindong_text_field.dart';

class XinDongProfileTagsYeMian extends StatefulWidget {
  final List<String> tags;
  final Function(List<String> tags) onUpdate;

  const XinDongProfileTagsYeMian({super.key, required this.tags, required this.onUpdate});

  @override
  State<XinDongProfileTagsYeMian> createState() => _XinDongProfileTagsYeMianState();
}

class _XinDongProfileTagsYeMianState extends State<XinDongProfileTagsYeMian> {
  final _mineHandle = XinDongWoDeHandle();
  final _controller = TextEditingController();
  late List<XinDongTagClass> _tagList = XinDongAll.instance.tagList;
  late List<XinDongTagClass> _selectList = [];

  void onUpdate() {
    _selectList = _tagList.where((element) => element.selected == 1).toList();
    List<int> ids = _selectList.map((e) => e.id).toList();
    List<String> list = _selectList.map((e) => e.name).toList();
    _mineHandle.userUpdateTags(tags: ids);
    widget.onUpdate(list);
  }

  Future<void> onCreated(String text) async {
    if (_selectList.length >= 10) {
      showToast("最多可添加10个标签");
      return;
    }
    if (TextUtil.isEmpty(text)) {
      return;
    }
    bool result = await _mineHandle.userCreateTag(tagName: text);
    if (result) {
      showToast("添加成功");
      _controller.text = "";
      _mathData();
    }
  }

  void _mathData() async {
    XinDongAll.instance.tagList = await _mineHandle.userTagsList();
    _tagList = XinDongAll.instance.tagList;
    _selectList = _tagList.where((element) => element.selected == 1).toList();
    setState(() {});
  }

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      _mathData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: XinDongAppBar("我的标签（${_selectList.length}/10）"),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
        behavior: HitTestBehavior.opaque,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: kCellHeight,
              width: 250,
              child: XinDongTextField(
                prefixIcon: const Icon(Icons.add_circle_outline, size: 26, color: DZColors.contentColor),
                suffixIcon: Container(
                  width: 50,
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "(${_controller.text.length}/6)",
                    style: const TextStyle(fontSize: 16, color: DZColors.placeholderColor),
                  ),
                ),
                hintText: "创建我自己的标签",
                inputFormatters: [LengthLimitingTextInputFormatter(6)],
                controller: _controller,
                onChanged: (text) => setState(() {}),
                onSubmitted: onCreated,
              ),
            ),
            commonDivider(indent: 15, endIndent: 15),
            Expanded(
              child: Container(
                alignment: Alignment.topLeft,
                padding: const EdgeInsets.all(15),
                child: Wrap(
                  spacing: 10,
                  runSpacing: 10,
                  children: _tagList.map((e) => _buildItem(e)).toList(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildItem(XinDongTagClass model) {
    return GestureDetector(
      onTap: () {
        if (model.selected == 0 && _selectList.length == 10) {
          showToast("最多可添加10个标签");
          return;
        }
        setState(() {
          model.selected = model.selected == 1 ? 0 : 1;
        });
        onUpdate();
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        height: 28,
        padding: const EdgeInsets.only(left: 8, right: 8),
        decoration: BoxDecoration(
          color: model.selected == 1 ? DZColors.mainLightColor : Colors.black12,
          borderRadius: BorderRadius.circular(28),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              model.name,
              style: TextStyle(
                fontSize: 15,
                color: model.selected == 1 ? DZColors.mainColor : DZColors.contentColor,
                height: 1.2,
              ),
            )
          ],
        ),
      ),
    );
  }
}
